package com.etrans.web.gps.business.report.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.report.service.PlatAlarmService;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.grid.FlexiGridUtil;
import com.mongodb.BasicDBObject;

/**
 * 平台报警分析
 * @author zhangw
 *
 */
@Controller
@RequestMapping("/report/platAlarm/*")
public class PlatAlarmController extends BaseController{
	
	private final static Logger logger = LoggerFactory.getLogger(PlatAlarmController.class);
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private PlatAlarmService platAlarm;
	
	/**
	 * 页面跳转入口
	 * @return
	 */
	@RequestMapping(value="getPlatAlarm.html")
	public ModelAndView getAlarmSynAnalysis(Model model){
		ModelAndView mv =new ModelAndView();
		mv.addObject("flag", false);
		mv.setViewName("views/business/report/platAlarm");
		return mv;
	}
	
	/**
	 * 点击柱状图关联表格数据
	 * @return 
	 */
	@ResponseBody
	@RequestMapping(value = "getTableData.html")
	public PageVo getTableChartData(String paramsGrid){
		try {
			Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
			String startTime = params.get("startTime")==null?"":params.get("startTime")+"";				//开始时间
			String endTime = params.get("endTime")==null?"":params.get("endTime")+"";					//结束时间
			String alarmType = params.get("alarmType")==null?"":params.get("alarmType")+"";				//报警类型
			//String queryType = params.get("queryType")==null?"":params.get("queryType")+"";			//查询方式
			//String queryContent = params.get("queryContent")==null?"":params.get("queryContent")+"";	//查询内容
			int page = params.get("page")==null?0:Integer.parseInt(params.get("page")+"");	
			int size = params.get("pageSize")==null?10:Integer.parseInt(params.get("pageSize")+"");
			int from = (page-1) * size;
			// 查询条件
			BasicDBObject query = new BasicDBObject();
			if (StringUtils.isNotBlank(alarmType)) {
				query.put("alarm_type", Integer.valueOf(alarmType));
			}
			List<Integer> areaIdList =commonService.queryAreaListById(this.getSysUser().getArea_id());
			query.put("area_id", new BasicDBObject("$in", areaIdList));
			PageVo pageVo = new PageVo();
			pageVo.setPage(page);
			List<String> days = DateUtil.getDates(startTime, endTime);
			List<Document> list = new ArrayList<Document>();
			int total = 0;
			for (String day : days) {
				String table = day.replace("-", "").substring(2);
				int count = from + list.size();
				if (count >= total && list.size() < size) {
					list.addAll(platAlarm.getTableDataList(query, table, count-total, size-list.size()));
				}
				total += platAlarm.getTableDataCount(query, table);
			}
			pageVo.setRows(list);
			pageVo.setTotal(total);
			return pageVo;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
	}
	
	/**
	 *
	 *@description  导出查询结果
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "exportQueryResult.html")
	public void exportQueryResult( HttpServletRequest request, HttpServletResponse response, String startTime, String endTime,
			String alarmType, String title, String StartPage, String EndPage, String PageSize,String colModel) {
		try {
			//获取参数
			List<String> colModelList = JSON.parseObject(colModel, List.class);
			int from = (Integer.parseInt(StartPage) - 1) * Integer.parseInt(PageSize);
			int size =(Integer.parseInt(EndPage) - Integer.parseInt(StartPage)+1) * Integer.parseInt(PageSize);
			//传入条件从MongoDB中查询出数据
			// 查询条件
			BasicDBObject query = new BasicDBObject();
			if (StringUtils.isNotBlank(alarmType)) {
				query.put("alarm_type", Integer.valueOf(alarmType));
			}
			List<Integer> areaIdList =commonService.queryAreaListById(this.getSysUser().getArea_id());
			query.put("area_id", new BasicDBObject("$in", areaIdList));
			List<String> days = DateUtil.getDates(startTime, endTime);
			List<Document> list = new ArrayList<Document>();
			int total = 0;
			for (String day : days) {
				String table = day.replace("-", "").substring(2);
				int count = from + list.size();
				if (count >= total && list.size() < size) {
					list.addAll(platAlarm.getTableDataList(query, table, count-total, size-list.size()));
					if (list.size()==size) {
						break;
					}
				}
				total += platAlarm.getTableDataCount(query, table);
			}
			//获取车辆颜色Map
			Map<String,Object> colorMap = new HashMap<String,Object>();
			List<HashMap<String, Object>> colorList = commonService.queryVehicleColorList(null);
			for (HashMap<String, Object> hashMap : colorList) {
				colorMap.put(String.valueOf(hashMap.get("id")), hashMap.get("name"));
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
			for(int i = 0; i < list.size(); i++){
				HashMap<String, Object> map = new HashMap<String, Object>();
				Document doc= list.get(i);
				map.put("vehicle_no", doc.getString("vehicle_no"));
				map.put("vehicle_color",  colorMap.get(doc.get("vehicle_color")+""));
				map.put("enterprise_name", doc.getString("enterprise_name"));
				map.put("platform_name", doc.getString("platform_name")) ;
				map.put("alarm_type", doc.getString("alarm_type"));
				map.put("alarm_src", "政府平台");
				map.put("alarm_time", sdf.format(doc.getDate("alarm_time")));
				rows.add(map);
			}
			List rowsList = new ArrayList<>();
			rowsList.add(rows);
			exportExl(request, response, title, removeHeadName(colModelList, -1, -1), rowsList, null);
		} catch (Exception e) {
			logger.error("导出位置获取失败",e);
		}
	}
}
